package com.hellobike.haxing.modules.shop.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.product.entity.City;
import com.hellobike.haxing.modules.product.entity.District;
import com.hellobike.haxing.modules.product.entity.Province;
import com.hellobike.haxing.modules.product.entity.Street;
import com.hellobike.haxing.modules.product.mapper.CityMapper;
import com.hellobike.haxing.modules.product.mapper.DistrictMapper;
import com.hellobike.haxing.modules.product.mapper.ProvinceMapper;
import com.hellobike.haxing.modules.product.mapper.StreetMapper;
import com.hellobike.haxing.modules.shop.entity.Shop;
import com.hellobike.haxing.modules.shop.mapper.ShopMapper;
import com.hellobike.haxing.modules.shop.model.ShopImportModel;
import com.hellobike.haxing.modules.shop.service.IShopService;
import com.hellobike.haxing.modules.user.entity.User;
import com.hellobike.haxing.modules.user.mapper.UserMapper;
import lombok.Cleanup;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 自提点
 * @Author: haxing-boot
 * @Date: 2020-02-03
 * @Version: V1.0
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private ProvinceMapper provinceMapper;
    @Autowired
    private CityMapper cityMapper;
    @Autowired
    private DistrictMapper districtMapper;
    @Autowired
    private StreetMapper streetMapper;
    @Autowired
    private ShopMapper shopMapper;

    @Override
    public List<Province> getOpenedProvinces() {
        return provinceMapper.getOpenedProvinces();
    }

    @Override
    public List<City> getOpenedCitiesByProvinceId(Long provinceId) {
        return cityMapper.getOpenedCitiesByProvinceId(provinceId);
    }

    @Override
    public List<City> getOpenedCitiesByProvinceIds(List<Long> provinceIdList) {
        return cityMapper.getOpenedCitiesByProvinceIds(provinceIdList);
    }

    @Override
    public List<City> getAllOpenedCities() {
        return cityMapper.getAllOpenedCities();
    }

    @Override
    public List<District> getOpenedDistrictsByCityId(Long cityId) {
        return districtMapper.getOpenedDistrictsByCityId(cityId);
    }

    @Override
    public List<District> getOpenedDistrictsByCityIds(List<Long> cityIdList) {
        return districtMapper.getOpenedDistrictsByCityIds(cityIdList);
    }

    @Override
    public List<Street> getOpenedStreetsByDistrictId(Long districtId) {
        return streetMapper.getOpenedStreetsByDistrictId(districtId);
    }

    @Override
    public List<Street> getOpenedStreetsByDistrictIds(List<Long> districtIdList) {
        return streetMapper.getOpenedStreetsByDistrictIds(districtIdList);
    }

    @Override
    public List<Shop> getShopsByStreetId(Long streetId) {
        return shopMapper.selectList(new QueryWrapper<Shop>().lambda().eq(Shop::getStreetId, streetId));
    }

    @Override
    public List<Shop> getShopsByStreetIds(List<Long> streetIdList) {
        return shopMapper.selectList(new QueryWrapper<Shop>().lambda().in(Shop::getStreetId, streetIdList));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateIncome(BigDecimal amount, Long shopId) {
        shopMapper.updateIncome(amount, shopId);
    }

    @Override
    public Result<String> openShop(Long id, String username) {
        Result<String> result = new Result<>();
        Shop shop = shopMapper.selectById(id);
        if (shop == null || !shop.getState().equals(2)) {
            return result.error500("店铺状态不对，不能开启");
        }
        Shop param = new Shop();
        param.setId(shop.getId());
        param.setState(1);
        shopMapper.updateById(param);
        return result.success("店铺开启成功");
    }

    @Override
    public Result<?> closeShop(Long id, String username) {
        Result<String> result = new Result<>();
        Shop shop = shopMapper.selectById(id);
        if (shop == null || !shop.getState().equals(1)) {
            return result.error500("店铺状态不对，不能关闭");
        }
        Shop param = new Shop();
        param.setId(shop.getId());
        param.setState(2);
        shopMapper.updateById(param);
        return result.success("店铺开启成功");
    }

    @Override
    public Result<?> audit(Long id, String username, Integer state, String reason, Long leadShopId, String bankCode) {
        Result<String> result = new Result<>();
        Shop shop = shopMapper.selectById(id);
        if (shop == null || shop.getState().equals(state)) {
            result.error500("操作失败，请重新加载数据 ");
            return result;
        } else {
            Shop param = new Shop();
            param.setState(state);
            param.setId(id);
            if (leadShopId != null && leadShopId > 0) {
                Shop leader = shopMapper.selectById(leadShopId);
                if (leader != null) {
                    param.setLeadShopId(leadShopId);
                    param.setLeadShopMobile(leader.getMobile());
                }
            }
            if (StringUtils.isNotBlank(bankCode)) {
                param.setBankCode(bankCode);
            }
            param.setReason(reason);
            shopMapper.updateById(param);
            result.success("");
        }
        return result;
    }

    @Override
    public Result<?> saveExtension(Shop shop) {
        /**
         * 不跟自己的账号比较手机号
         */
        LambdaQueryWrapper<Shop> lambdaQueryWrapper = new QueryWrapper<Shop>()
                .lambda().eq(Shop::getMobile, shop.getMobile());
        if (shop.getId() != null) {
            lambdaQueryWrapper.ne(Shop::getId, shop.getId());
        }
        Integer count = this.shopMapper.selectCount(lambdaQueryWrapper);
        if (count > 0) {
            return Result.error("手机号已经存在");
        }
        shop.setShopName(shop.getRealName() + "推广店铺");
        User user = userMapper.selectOne(new QueryWrapper<User>()
                .lambda().eq(User::getMobile, shop.getMobile()).orderByDesc(User::getId)
                .eq(User::getDeleted, 0).last("limit 1"));
        if (user == null) {
            user = new User();
            user.setMobile(shop.getMobile());
            user.setUserType(3);
            userMapper.insert(user);
        }
        if (shop.getLeadShopId() != null && shop.getLeadShopId() > 0) {
            Shop leader = shopMapper.selectById(shop.getLeadShopId());
            if (leader != null) {
                shop.setLeadShopMobile(leader.getMobile());
            }
        }
        shop.setUserId(user.getId());
        shop.setState(1);
        shop.setUpdateTime(new Date());
        if (shop.getId() != null) {
            shopMapper.updateById(shop);
        } else {
            shopMapper.insert(shop);
        }
        return Result.ok("推广人保存成功");
    }

    @Override
    @Transactional
    public Result<?> importShop(MultipartFile file) throws IOException {
        List<Province> provinceList = provinceMapper.selectList(null);
        List<City> cityList = cityMapper.selectList(null);
        List<District> districtList = districtMapper.selectList(null);
        Map<String, Long> provinceMap = provinceList.stream().collect(Collectors.toMap(Province::getName, province -> province.getId(), (v1, v2) -> v1));
        Map<String, Long> cityMap = cityList.stream().filter(city -> city != null).collect(Collectors.toMap(City::getName, city -> city.getId(), (v1, v2) -> v1));
        Map<String, Long> districtMap = districtList.stream().filter(district -> district != null).collect(Collectors.toMap(District::getName, district -> district.getId(), (v1, v2) -> v1));
        @Cleanup InputStream in = file.getInputStream();
        @Cleanup("finish") ExcelReader excelReader = EasyExcel.read(in).build();
        LinkedHashSet<String> errorTips = new LinkedHashSet<>();
        List<Shop> shopList = new ArrayList<>();
        ReadSheet spuSheet = EasyExcel.readSheet(0).head(ShopImportModel.class).registerReadListener(new AnalysisEventListener<ShopImportModel>() {
            @Override
            public void invoke(ShopImportModel shopImportModel, AnalysisContext context) {
                String position = "<span style='color: red'>[表-" + (1) + " 行-" + (context.getCurrentRowNum() + 1) + "] </span>";
//                if (StringUtils.isBlank(shopImportModel.getShopName()) || StringUtils.isBlank(shopImportModel.getRealName()) ||
//                        StringUtils.isBlank(shopImportModel.getMobile())
//                        || StringUtils.isBlank(shopImportModel.getWechatNo()) ||
//                        StringUtils.isBlank(shopImportModel.getRegion())) {
//                    errorTips.add(position + "必填项不能为空；");
//                }
                //类型转换
                Shop shop = new Shop();
                shop.setShopName(shopImportModel.getShopName());
                shop.setStreetId(0L);
                shop.setProvinceId(provinceMap.get(shopImportModel.getProvince()));
                shop.setCityId(cityMap.get(shopImportModel.getCity()));
                shop.setDistrictId(districtMap.get(shopImportModel.getDistrict()));
                shop.setShopType(1);
                shop.setBankCardNo(shopImportModel.getBankCardNo());
                shop.setBankCardOwner(shopImportModel.getBankName());
                shop.setAddress(shopImportModel.getAddress());
                shop.setBusinessTime(shopImportModel.getBussinessTime());
                shop.setIdNo(shopImportModel.getIdNo());
                shop.setMobile(shopImportModel.getMobile());
                shop.setWechatNo(shopImportModel.getWechatNo());
                shop.setState(1);
                shop.setRealName(shopImportModel.getRealName());
                if (StringUtils.isNotBlank(shopImportModel.getRegion())) {
                    String[] posistions = shopImportModel.getRegion().split(",");
                    shop.setGeoLon(BigDecimal.valueOf(Double.valueOf(posistions[0])));
                    shop.setGeoLat(BigDecimal.valueOf(Double.valueOf(posistions[1])));
                }
                shopList.add(shop);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            }
        }).build();
        excelReader.read(spuSheet);
        if (!CollectionUtils.isEmpty(shopList)) {
            for (Shop shop : shopList) {
                User user = userMapper.selectOne(new QueryWrapper<User>()
                        .lambda().eq(User::getMobile, shop.getMobile()).orderByDesc(User::getId).last("limit 1"));
                if (user == null) {
                    user = new User();
                    user.setMobile(shop.getMobile());
                    user.setUserType(2);
                    user.setNickname(shop.getRealName());
                    user.setRealname(shop.getRealName());
                    userMapper.insert(user);
                }
                shop.setUserId(user.getId());
                shopMapper.insert(shop);
            }
        }
        return Result.ok("");
    }

    private void addErrorInfoIf(boolean condition, LinkedHashSet<String> errorTips, String errorInfo) {
        if (condition) {
            errorTips.add(errorInfo);
        }
    }

    @Autowired
    private UserMapper userMapper;
}
